package mdm.led.service.impl;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import mdm.led.dao.DepartmentMapper;
import mdm.led.dao.DopeMapper;
import mdm.led.dao.FourDetailsMapper;
import mdm.led.dao.FourInspectorMapper;
import mdm.led.dao.FourItemMapper;
import mdm.led.dao.UserMapper;
import mdm.led.entity.Dope;
import mdm.led.entity.InspectorList;
import mdm.led.entity.User;
import mdm.led.entity.four.FourDatilsParam;
import mdm.led.entity.four.FourDetails;
import mdm.led.entity.four.FourInspector;
import mdm.led.entity.four.FourInspectorRequest;
import mdm.led.entity.four.FourItem;
import mdm.led.service.FourInspectorService;
import mdm.led.util.ListToString;

/**
 *
 * @author :Monarch丿He
 * @date :2018年11月2日
 * @explain :督查四必 业务 接口实现
 */
@Service("fourInspectorServiceImpl")
public class FourInspectorServiceImpl implements FourInspectorService {

	@Autowired
	private FourInspectorMapper fourInspectorDao;
	@Autowired
	private FourItemMapper fourItemDao;
	@Autowired
	private FourDetailsMapper fourDetailsDao;
	@Autowired
	private DopeMapper dopeDao;
	@Autowired
	private UserMapper userDao;

	@Override
	public Boolean addFourInspector(FourInspector fourInspector) {
		// 标识
		Boolean iRet = false;
		// 前端传入的 检查项目集合
		List<FourItem> list = fourInspector.getFourItems();
		try {
			int i = fourInspectorDao.addFourInspector(fourInspector);

			if (i > 0) {
				for (FourItem itme : list) {
					// 将督查表id 存入 检查项 对应督查 ID
					itme.setfourTableId(fourInspector.getInspectorId());
					// 存库
					fourItemDao.addFourItem(itme);
				}
			}
			String write = fourInspector.getObjectId();
			if (write != null && write != "") {
				String[] department = write.split(",");
				// 当前部门下所有 负责人 和主要负责人
				List<User> users = new ArrayList<>();
				for (String item : department) {
					List<User> findChargeMan1 = userDao.findChargeMan(Integer.parseInt(item), "主要负责人");
					if(findChargeMan1.size() > 0){
						users.addAll(findChargeMan1);
					}
					List<User> findChargeMan2 = userDao.findChargeMan(Integer.parseInt(item), "负责人");
					if(findChargeMan2.size() > 0){
						users.addAll(findChargeMan2);
					}
				}
				// 转换为数组
				String[] writeArr = new String[users.size()];
				for (int j = 0; j < users.size(); j++) {
					writeArr[j] = users.get(j).getcUserId().toString();
				}
				FourDetails fourDetails = null;
				List<String> itemIds = null;
				for (String item : writeArr) {
					itemIds = new ArrayList<>();
					for (FourItem it : list) {
						// it.setfourTableId(fourInspector.getInspectorId());
						it.setfourTableId(0);
						// 存库
						fourItemDao.addFourItem(it);
						itemIds.add(String.valueOf(it.getFourItmeId()));
					}
					// 添加详情表
					fourDetails = new FourDetails();
					fourDetails.setTableId(fourInspector.getInspectorId());
					fourDetails.setWriteMan(Integer.parseInt(item));
					fourDetails.setEstate(1);
					// 转化为 字符串
					fourDetails.setItems(ListToString.stringListToString(itemIds, ","));
					fourDetailsDao.addFourDetails(fourDetails);
				}
			}

			iRet = true;
		} catch (Exception e) {
			///
		}
		return iRet;
	}
	

	@Override
	public int updateFourInspectorStatus(Integer id) {

		return fourInspectorDao.updateFourInspectorStatus(id);
	}

	@Override
	public List<FourInspectorRequest> findAllFourInspector(String name) {
		// 需要返回的督查列表信息
		List<FourInspectorRequest> inspectorRequests = new ArrayList<>();
		List<FourInspector> inspectors = fourInspectorDao.findAllFourInspector();
		// 返回督查表详情
		FourInspectorRequest request = null;

		String checkMans = "";
		for (FourInspector item : inspectors) {
			if (name != null && name != "") {
				if (item.getName().indexOf(name) == -1) {
					continue;
				}
			}
			request = new FourInspectorRequest();
			request.setInspectorId(item.getInspectorId());
			request.setTableName(item.getName());
			request.setEndTime(item.getStartTime());
			request.setStatus(String.valueOf(item.getStatus()));

			// get 填写人拼接字符串 并解析成 集合
			checkMans = item.getObjectId();
			// 判断填写人是否为空
			if (checkMans != null && checkMans != "") {
				List<String> objects = new ArrayList<>();
				User user = null;
				String[] mans = checkMans.split(",");
				for (String str : mans) {
					user = userDao.selectById(Integer.parseInt(str));
					if(user != null ){
						objects.add(user.getcNickname());
					}
				}
				// 添加到当前项
				request.setObjects(objects);
			}
			// 添加到返回信息的集合
			inspectorRequests.add(request);
		}
		return inspectorRequests;
	}

	@Override
	public FourInspectorRequest findFourInspector(Integer id) {
		// 需要返回到前端的对象
		FourInspectorRequest request = new FourInspectorRequest();
		// 表信息
		FourInspector four = fourInspectorDao.findFourInspector(id);
		// 检查项
		List<FourItem> fourItems = fourItemDao.findFourItemsByTid(id);
		request.setFourItems(fourItems);
		request.setInspectorId(four.getInspectorId());
		request.setTableName(four.getName());
		request.setEndTime(four.getStartTime());
		request.setStatus(String.valueOf(four.getStatus()));

		// get 填写人拼接字符串 并解析成 集合
		String checkMans = four.getObjectId();
		// 判断填写人是否为空
		if (checkMans != null && checkMans != "") {
			List<String> objects = new ArrayList<>();
			User user = null;
			String[] mans = checkMans.split(",");
			for (String str : mans) {
				user = userDao.selectById(Integer.parseInt(str));
				if(user != null){
					objects.add(user.getcNickname());
				}
			}
			// 添加到当前项
			request.setObjects(objects);
		}

		return request;
	}

	@Override
	public List<InspectorList> findInspectorList(String name) {

		List<InspectorList> list = fourDetailsDao.findInspectorList(name);
		int via = 0;
		int tote = 0;
		double score = 0;
		DecimalFormat df = new DecimalFormat("#.00");
		for (InspectorList item : list) {
			// (1:未完成,2:已完成,3:通过,4:未通过)
			// 设定当前状态为 完成
			item.setEstate(1);
			item.setDone(fourDetailsDao.findFruitByEstate(item));
			// 设定当前状态为 未完成
			item.setEstate(2);
			item.setNodone(fourDetailsDao.findFruitByEstate(item));
			// 设定当前状态为 通过
			item.setEstate(3);
			item.setVia(fourDetailsDao.findFruitByEstate(item));
			// 设定当前状态为 未通过
			item.setEstate(4);
			item.setNovia(fourDetailsDao.findFruitByEstate(item));
			// 取出当前通过总次数
			via = item.getVia();
			// 取出当前 总次数
			tote = item.getTote();
			// 分数
			score = Double.parseDouble(df.format(via / Double.parseDouble(Integer.toString(tote))));
			item.setGrade(score);
		}

		return list;
	}

	/**
	 * 如果是督查角色登录 传入 督查 {登录标识(iRet:1为督查角色
	 * 2:普通用户),部门id,状态(1:未完成,2:已完成,3:通过,4:未通过),用户名(可选)} ," + " 如果不是督查角色 需要传入
	 * {登录标识(iRet:1为督查角色 2:普通用户), 状态(1:未完成,2:已完成,3:通过,4:未通过),用户 id,用户名(可选)}
	 */
	public List<FourDetails> findDetailsApp(FourDatilsParam fourDatilsParam) {

		List<FourDetails> four = fourDetailsDao.findFourDetails(fourDatilsParam);
		// 需要返回的集合
		List<FourDetails> fourDetails = new ArrayList<>();
		// 当前时间
		Date newTime = new Date();
		// 日期格式
		SimpleDateFormat si = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			newTime = si.parse(si.format(newTime));
		} catch (ParseException e1) {
			e1.printStackTrace();
		}
		Date oldTime = null;
		// 督查表 ID
		FourInspector fourInspector = null;
		for (FourDetails item : four) {
			fourInspector = fourInspectorDao.findFourInspector(item.getTableId());
			// 截止日期
			try {
				oldTime = si.parse(si.format(fourInspector.getStartTime()));
			} catch (ParseException e) {
				e.printStackTrace();
			}
			// flag，等于0日期相等，大于0表示在当前时间之后，小于0在当前时间之前
			int flag = oldTime.compareTo(newTime);
			if (flag < 0 && item.getEstate() == 1) {
				continue;
			}
			item.setInspector(fourInspector);
			fourDetails.add(item);
		}

		return fourDetails;
	}

	/**
	 * 如果是督查角色登录 传入 督查 {登录标识(iRet:1为督查角色
	 * 2:普通用户),部门id,状态(1:未完成,2:已完成,3:通过,4:未通过),用户名(可选)} ," + " 如果不是督查角色 需要传入
	 * {登录标识(iRet:1为督查角色 2:普通用户), 状态(1:未完成,2:已完成,3:通过,4:未通过),用户 id,用户名(可选)}
	 */
	public List<FourDetails> findDetailsWeb(FourDatilsParam fourDatilsParam) {

		List<FourDetails> four = fourDetailsDao.findFourDetails(fourDatilsParam);
		// 需要返回的集合
		List<FourDetails> fourDetails = new ArrayList<>();
		// 当前时间
		Date newTime = new Date();
		// 日期格式
		SimpleDateFormat si = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			newTime = si.parse(si.format(newTime));
		} catch (ParseException e1) {
			e1.printStackTrace();
		}
		// Date oldTime = null;
		// 督查表 ID
		FourInspector fourInspector = null;
		for (FourDetails item : four) {
			fourInspector = fourInspectorDao.findFourInspector(item.getTableId());
			/*
			 * // 截止日期 try { oldTime =
			 * si.parse(si.format(fourInspector.getStartTime())); } catch
			 * (ParseException e) { e.printStackTrace(); }
			 */
			/*
			 * // flag，等于0日期相等，大于0表示在当前时间之后，小于0在当前时间之前 int flag =
			 * oldTime.compareTo(newTime); if (flag < 0 && item.getEstate() ==
			 * 1) { continue; }
			 */
			item.setInspector(fourInspector);
			fourDetails.add(item);
		}

		return fourDetails;
	}

	@Override
	public FourDetails findDetailsById(Integer id) {
		// 详情表
		FourDetails fourDetails = fourDetailsDao.findFourDetailsById(id);
		// 督查表 id
		int tableId = fourDetails.getTableId();
		// 督查表 ID
		FourInspector fourInspector = fourInspectorDao.findFourInspector(tableId);
		fourDetails.setInspector(fourInspector);
		// 检查项 字符
		String itemsStr = fourDetails.getItems();
		if (itemsStr != null && itemsStr != "") {
			String[] itemsArr = itemsStr.split(",");
			FourItem item = null;
			// 检查项集合
			List<FourItem> list = new ArrayList<FourItem>();
			for (String str : itemsArr) {
				item = fourItemDao.findFourItemById(Integer.parseInt(str));
				if(item != null){
					list.add(item);
				}
			}
			fourDetails.setItemList(list);

		}

		return fourDetails;
	}

	@Override
	public boolean checkComplete(FourDetails fourDetails) {
		boolean iRet = false;
		// 所有检查项
		List<FourItem> fourItems = fourDetails.getItemList();
		try {
			// 操作所有项
			for (FourItem fourItem : fourItems) {
				fourItemDao.updateFourItem(fourItem);
			}
			fourDetails.setEstate(2);
			fourDetailsDao.updateFourDetails(fourDetails);
			iRet = true;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return iRet;
	}

	@Override
	public Boolean InspectorCheck(Integer detailsId, Integer estate, String cause) {

		Boolean iRet = false;
		try {
			// 入参 map 集合 {详情表ID,状态,原因}
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("detailsId", detailsId);
			map.put("estate", estate);
			map.put("cause", cause);
			fourDetailsDao.InspectorCheck(map);
			// 未通过打回去重写
			if (estate == 4) {
				// ***{生成 一张新的 详情表}**
				// 详情表
				FourDetails fourDetails = fourDetailsDao.findFourDetailsById(detailsId);
				// 原因
				fourDetails.setCause(null);
				// 默认状态为完成
				fourDetails.setEstate(1);
				// 时间清空
				fourDetails.setWriteTime(null);

				// 督查表 id
				int tableId = fourDetails.getTableId();
				// 检查项 字符
				String itemsStr = fourDetails.getItems();
				String[] itemsArr = itemsStr.split(",");
				// 督查表 ID
				FourInspector fourInspector = fourInspectorDao.findFourInspector(tableId);
				FourItem item = null;
				List<Integer> list = new ArrayList<Integer>();
				for (String str : itemsArr) {
					item = fourItemDao.findFourItemById(Integer.parseInt(str));
					item.setValue(null);
					fourItemDao.addFourItem(item);
					// 生成新的 检查项
					list.add(item.getFourItmeId());
				}
				fourDetails.setItems(ListToString.integerListToString(list, ","));
				fourDetails.setInspector(fourInspector);

				// 发送消息
				// 接收人
				List<Integer> list2 = new ArrayList<>();
				// 消息实例
				Dope dope = new Dope();
				User presentUser = userDao.selectById(fourDetails.getWriteMan());
				// 填表人
				dope.setWriteMan(presentUser.getcNickname());
				List<User> answerMan = userDao.findChargeMan(presentUser.getDepartmentId(),"负责人");
				if (answerMan.size() > 0) {
					User a = answerMan.get(0);
					// 二级责任人
					dope.setTwoDutyMan(a.getcNickname());
					list2.add(answerMan.get(0).getcUserId());
				}
				list2.add(fourDetails.getWriteMan());

				if (list2.size() > 0) {
					dope.setTime(new Date());
					dope.setTitle(fourInspector.getName());
					dope.setVisual(1);
					dope.setStatus(2);
					dope.setIfPop(1);
					dope.setPigment(1);
					dope.setType(2);
					dope.setContent(cause);
					for (Integer userid : list2) {
						dope.setReceiveMan(String.valueOf(userid));
						// 添加到数据库
						dopeDao.addAppointManDope(dope);

					}

				}

			}

			iRet = true;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return iRet;
	}

}
